import React, { useState } from 'react';
import { NavBar, Space, Input, Button, Toast, Tabs } from 'antd-mobile'
import { useNavigate } from 'react-router-dom';
import { API_CONFIG, request } from '../config/api';
import { setRiderInfo, isLoggedIn, clearRiderInfo } from '../utils/auth';
import './Login.css';

function Login() {
    const navigate = useNavigate();
    const [activeTab, setActiveTab] = useState('login');
    const [loading, setLoading] = useState(false);

    // 登录表单状态
    const [loginForm, setLoginForm] = useState({
        phone: '',
        password: ''
    });

    // 注册表单状态
    const [registerForm, setRegisterForm] = useState({
        name: '',
        phone: '',
        password: '',
        confirmPassword: '',
        gender: '男',
        age: ''
    });

    // 处理登录表单输入
    const handleLoginInputChange = (field, value) => {
        setLoginForm(prev => ({
            ...prev,
            [field]: value
        }));
    };

    // 处理注册表单输入
    const handleRegisterInputChange = (field, value) => {
        setRegisterForm(prev => ({
            ...prev,
            [field]: value
        }));
    };

    // 验证手机号格式
    const validatePhone = (phone) => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    };

    // 验证密码长度
    const validatePassword = (password) => {
        return password.length >= 6;
    };

    // 登录处理
    const handleLogin = async () => {
        try {
            // 表单验证
            if (!loginForm.phone.trim()) {
                Toast.show({ content: '请输入手机号' });
                return;
            }
            if (!validatePhone(loginForm.phone)) {
                Toast.show({ content: '请输入正确的手机号格式' });
                return;
            }
            if (!loginForm.password.trim()) {
                Toast.show({ content: '请输入密码' });
                return;
            }

            setLoading(true);

            const response = await request(API_CONFIG.RIDER.LOGIN, {
                method: 'POST',
                body: JSON.stringify({
                    phone: loginForm.phone.trim(),
                    password: loginForm.password
                })
            });

            if (response.code === 0) {
                Toast.show({ content: '登录成功' });
                
                // 保存骑手信息到本地存储
                setRiderInfo(response.data.rider);
                
                // 根据骑手状态跳转到不同页面
                if (response.data.rider.status === 'ACTIVE') {
                    navigate('/layout/home');
                } else if (response.data.rider.status === 'PENDING') {
                    navigate('/pending');
                } else {
                    Toast.show({ content: '账户状态异常，请联系管理员' });
                    // 清除无效的登录信息
                    clearRiderInfo();
                }
            } else {
                Toast.show({ content: response.message || '登录失败' });
            }
        } catch (error) {
            console.error('登录错误:', error);
            Toast.show({ content: error.message || '登录失败，请稍后重试' });
        } finally {
            setLoading(false);
        }
    };

    // 注册处理
    const handleRegister = async () => {
        try {
            // 表单验证
            if (!registerForm.name.trim()) {
                Toast.show({ content: '请输入姓名' });
                return;
            }
            if (!registerForm.phone.trim()) {
                Toast.show({ content: '请输入手机号' });
                return;
            }
            if (!validatePhone(registerForm.phone)) {
                Toast.show({ content: '请输入正确的手机号格式' });
                return;
            }
            if (!registerForm.password.trim()) {
                Toast.show({ content: '请输入密码' });
                return;
            }
            if (!validatePassword(registerForm.password)) {
                Toast.show({ content: '密码长度至少6位' });
                return;
            }
            if (registerForm.password !== registerForm.confirmPassword) {
                Toast.show({ content: '两次输入的密码不一致' });
                return;
            }
            if (registerForm.age && (registerForm.age < 16 || registerForm.age > 70)) {
                Toast.show({ content: '年龄必须在16-70岁之间' });
                return;
            }

            setLoading(true);

            const response = await request(API_CONFIG.RIDER.REGISTER, {
                method: 'POST',
                body: JSON.stringify({
                    name: registerForm.name.trim(),
                    phone: registerForm.phone.trim(),
                    password: registerForm.password,
                    gender: registerForm.gender,
                    age: registerForm.age ? parseInt(registerForm.age) : undefined
                })
            });

            if (response.code === 0) {
                Toast.show({ content: '注册成功，请等待管理员审核' });
                
                // 清空注册表单
                setRegisterForm({
                    name: '',
                    phone: '',
                    password: '',
                    confirmPassword: '',
                    gender: '男',
                    age: ''
                });
                
                // 切换到登录页
                setActiveTab('login');
            } else {
                Toast.show({ content: response.message || '注册失败' });
            }
        } catch (error) {
            console.error('注册错误:', error);
            Toast.show({ content: error.message || '注册失败，请稍后重试' });
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="login-container">
            <NavBar backArrow={false} className="login-navbar">
                骑手登录
            </NavBar>

            <div className="login-content">
                <div className="login-header">
                    <h2>欢迎使用骑手端</h2>
                    <p>请登录或注册您的账户</p>
                </div>

                <Tabs 
                    activeKey={activeTab} 
                    onChange={setActiveTab}
                    className="login-tabs"
                >
                    <Tabs.Tab title="登录" key="login">
                        <div className="login-form">
                            <Space direction="vertical" block>
                                <Input
                                    placeholder="请输入手机号"
                                    value={loginForm.phone}
                                    onChange={(value) => handleLoginInputChange('phone', value)}
                                    type="tel"
                                    maxLength={11}
                                />
                                <Input
                                    placeholder="请输入密码"
                                    value={loginForm.password}
                                    onChange={(value) => handleLoginInputChange('password', value)}
                                    type="password"
                                    maxLength={20}
                                />
                                <Button
                                    block
                                    color="primary"
                                    size="large"
                                    loading={loading}
                                    onClick={handleLogin}
                                >
                                    登录
                                </Button>
                            </Space>
                        </div>
                    </Tabs.Tab>

                    <Tabs.Tab title="注册" key="register">
                        <div className="register-form">
                            <Space direction="vertical" block>
                                <Input
                                    placeholder="请输入姓名"
                                    value={registerForm.name}
                                    onChange={(value) => handleRegisterInputChange('name', value)}
                                    maxLength={20}
                                />
                                <Input
                                    placeholder="请输入手机号"
                                    value={registerForm.phone}
                                    onChange={(value) => handleRegisterInputChange('phone', value)}
                                    type="tel"
                                    maxLength={11}
                                />
                                <Input
                                    placeholder="请输入密码（至少6位）"
                                    value={registerForm.password}
                                    onChange={(value) => handleRegisterInputChange('password', value)}
                                    type="password"
                                    maxLength={20}
                                />
                                <Input
                                    placeholder="请确认密码"
                                    value={registerForm.confirmPassword}
                                    onChange={(value) => handleRegisterInputChange('confirmPassword', value)}
                                    type="password"
                                    maxLength={20}
                                />
                                <div className="form-row">
                                    <select
                                        value={registerForm.gender}
                                        onChange={(e) => handleRegisterInputChange('gender', e.target.value)}
                                        className="gender-select"
                                    >
                                        <option value="男">男</option>
                                        <option value="女">女</option>
                                        <option value="其他">其他</option>
                                    </select>
                                    <Input
                                        placeholder="年龄（可选）"
                                        value={registerForm.age}
                                        onChange={(value) => handleRegisterInputChange('age', value)}
                                        type="number"
                                        min="16"
                                        max="70"
                                    />
                                </div>
                                <Button
                                    block
                                    color="primary"
                                    size="large"
                                    loading={loading}
                                    onClick={handleRegister}
                                >
                                    注册
                                </Button>
                            </Space>
                        </div>
                    </Tabs.Tab>
                </Tabs>
            </div>
        </div>
    );
}

export default Login;
